# _*_ coding:utf-8 _*_
# @Time  : 2022.06.18
# @Author: zizlee
import datetime

from fastapi import APIRouter, Query
from v1_all_api.all_utils import datetime_utils
from v1_all_api.all_response import AllResponse

from db import FAConnection


variety_quotes_api = APIRouter()


@variety_quotes_api.get('/daily/')  # 品种的日行情
async def get_variety_daily_quotes(start: str = Query(...), end: str = Query(...),
                                   variety: str = Query(None), contract: str = Query(None)):
    start_ts = datetime_utils.auth_datetime_string(start, f='%Y%m%d', ts=True)
    end_ts = datetime_utils.auth_datetime_string(end, f='%Y%m%d', ts=True)
    if not all([start_ts, end_ts]):
        return AllResponse.validate_error(msg='日期格式错误!')
    variety_en = variety if variety else 'V'
    contract = contract if contract else 'C'
    sql = """
        SELECT id,quotes_ts,variety_en,contract,close_price,settlement 
        FROM dat_futures_daily_quotes 
        WHERE quotes_ts>=%s AND quotes_ts<=%s 
          AND IF('V'=%s,TRUE,variety_en=%s) AND IF('C'=%s,TRUE,contract=%s); 
    """
    prm = (start_ts, end_ts, variety_en, variety_en, contract, contract)
    db_conn = FAConnection()
    records = db_conn.query(sql, param=prm)
    for item in records:
        item['quote_date'] = datetime.datetime.fromtimestamp(item['quotes_ts']).strftime('%Y-%m-%d')
    return AllResponse.operate_successfully(data=records)



